//
//  HUTextView.m
//  YY键盘
//
//  Created by hu on 16/5/27.
//  Copyright © 2016年 hu. All rights reserved.
//

#define KMinHeight 45.0f
#define KYYKeyBoard [YYKeyboardManager defaultManager]
#define kFunctionViewHeight 210.f
#define SCREEN_Height_HU [[UIScreen mainScreen]bounds].size.height
#import "HUTextView.h"
#import "HUChatMoreView.h"
#import "HUFaceView.h"
#import "Masonry.h"
#import "YYKeyboardManager.h"
#import "HPGrowingTextView.h"
@interface HUTextView()<YYKeyboardObserver,HPGrowingTextViewDelegate,HUChatMoreViewDelegate,HUChatMoreViewDataSource,HUChatFaceViewDelegate,UINavigationControllerDelegate, UIImagePickerControllerDelegate>
@property (nonatomic, weak  ) UIView            * superView;/**< 父视图 */
@property (nonatomic, assign) CGRect            superFrame;
@property (strong, nonatomic) UIButton          *voiceButton;/**< 切换录音模式按钮 */
@property (strong, nonatomic) UIButton          *voiceRecordButton;/**< 录音按钮 */
@property (strong, nonatomic) UIButton          *faceButton;/**< 表情按钮 */
@property (strong, nonatomic) UIButton          *moreButton;/**< 更多按钮 */
@property (strong, nonatomic) HPGrowingTextView *textView;/**< 输入框*/
@property (strong, nonatomic) HUFaceView        *faceView;/**< 表情视图*/
@property (nonatomic, strong) HUChatMoreView    *moreView;/**< 更多视图*/

@property (copy, nonatomic  ) NSString          *inputText;

@end
@implementation HUTextView
- (instancetype)initWithController:(UIViewController *)controller {
    if (self = [super init]) {
        self.superFrame = controller.view.frame;
        self.superView = controller.view;
        [self setup];
        [KYYKeyBoard addObserver:self];
    }
    return self;
}
- (instancetype)initWithView:(UIView *)view {
    if (self = [super init]) {
        self.superFrame = view.frame;
        self.superView = view;
        [self setup];
        [KYYKeyBoard addObserver:self];
    }
    return self;
}
- (void)endInputing {
    [self showViewWithType:HUFunctionViewShowNothing];
}
-(void)dealloc{
    [KYYKeyBoard removeObserver:self];
}

- (void)setup {
    [self updateSelfFrame];
    [self addSubview:self.voiceButton];
    [self addSubview:self.faceButton];
    [self addSubview:self.moreButton];
    [self addSubview:self.textView];
    [self addSubview:self.voiceRecordButton];
    [self updateUIFrame];
}
- (void)updateSelfFrame {
    self.backgroundColor = [UIColor whiteColor];
//    self.frame = CGRectMake(0, self.superFrame.size.height - KMinHeight, self.superFrame.size.width, KMinHeight);
    [self setFrame: CGRectMake(0, self.superFrame.size.height - KMinHeight, self.superFrame.size.width, KMinHeight) animated:NO];
}
#pragma mark 更新UI布局
- (void)updateUIFrame {
    UIImageView *topLine = [[UIImageView alloc] init];
    topLine.backgroundColor = [UIColor colorWithRed:184/255.0f green:184/255.0f blue:184/255.0f alpha:1.0f];
    [self addSubview:topLine];
//    topLine.frame = CGRectMake(0, 0, self.frame.size.width, 0.5);
    [topLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.mas_left);
        make.right.equalTo(self.mas_right);
        make.top.equalTo(self.mas_top);
        make.height.mas_equalTo(@.5f);
    }];

}
- (void)updateConstraints{
    [super updateConstraints];
    [self.voiceButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.mas_left).with.offset(10);
        make.bottom.equalTo(self.mas_bottom).with.offset(-10);
        make.width.equalTo(self.voiceButton.mas_height);
    }];
    
    [self.moreButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.mas_right).with.offset(-10);
        make.bottom.equalTo(self.mas_bottom).with.offset(-10);
        make.width.equalTo(self.moreButton.mas_height);
    }];
    
    [self.faceButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.moreButton.mas_left).with.offset(-10);
        make.bottom.equalTo(self.mas_bottom).with.offset(-10);
        make.width.equalTo(self.faceButton.mas_height);
    }];
    
    [self.textView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.voiceButton.mas_right).with.offset(10);
        make.right.equalTo(self.faceButton.mas_left).with.offset(-10);
        make.top.equalTo(self.mas_top).with.offset(4);
        make.bottom.equalTo(self.mas_bottom).with.offset(-4);
    }];
    [self.voiceRecordButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.voiceButton.mas_right).with.offset(10);
        make.right.equalTo(self.faceButton.mas_left).with.offset(-10);
        make.top.equalTo(self.mas_top).with.offset(4);
        make.bottom.equalTo(self.mas_bottom).with.offset(-4);
    }];
}
- (void)keyboardChangedWithTransition:(YYKeyboardTransition)transition {
    CGRect kbFrame = [KYYKeyBoard convertRect:transition.toFrame toView:self.superView];

    __weak typeof(self)weakSelf = self;
    [UIView animateWithDuration:transition.animationDuration delay:0 options:transition.animationOption animations:^{
        CGRect textframe = weakSelf.frame;
        textframe.size.width = kbFrame.size.width;
        textframe.origin.y = kbFrame.origin.y - textframe.size.height;
//        weakSelf.frame = textframe;
        [weakSelf setFrame:textframe animated:NO];
    } completion:^(BOOL finished) {
        
    }];
}
- (void)initTextViewFrame {
    __weak typeof(self)weakSelf = self;
    [UIView animateWithDuration:0.3 animations:^{
        CGRect textframe = weakSelf.frame;
        textframe.origin.y = weakSelf.superFrame.size.height - KMinHeight;
        textframe.size.height = KMinHeight;
        [weakSelf setFrame:textframe animated:NO];
    }];
}
#pragma mark button点击事件
- (void)buttonAction:(UIButton *)button{
    self.inputText = self.textView.text;
    HUFunctionViewShowType showType = button.tag;
    
    //更改对应按钮的状态
    if (button == self.faceButton) {
        [self.faceButton setSelected:!self.faceButton.selected];
        [self.moreButton setSelected:NO];
        [self.voiceButton setSelected:NO];
    }else if (button == self.moreButton){
        [self.faceButton setSelected:NO];
        [self.moreButton setSelected:!self.moreButton.selected];
        [self.voiceButton setSelected:NO];
    }else if (button == self.voiceButton){
        [self.faceButton setSelected:NO];
        [self.moreButton setSelected:NO];
        [self.voiceButton setSelected:!self.voiceButton.selected];
        [self.textView resignFirstResponder];
    }
    
    if (!button.selected) {
        showType = HUFunctionViewShowKeyboard;
        [self.textView becomeFirstResponder];
    }else{
        self.inputText = self.textView.text;
    }
    [self showViewWithType:showType];
}
- (void)showViewWithType:(HUFunctionViewShowType)showType{
    //显示对应的View
    [self showMoreView:showType == HUFunctionViewShowMore && self.moreButton.selected];
    [self showVoiceView:showType == HUFunctionViewShowVoice && self.voiceButton.selected];
    [self showFaceView:showType == HUFunctionViewShowFace && self.faceButton.selected];
    
    switch (showType) {
        case HUFunctionViewShowNothing:
        {
            [self initTextViewFrame];
        }
        case HUFunctionViewShowVoice:
        {
            self.inputText = self.textView.text;
            self.textView.text = nil;
            [self.textView resignFirstResponder];
            [self initTextViewFrame];
        }
            break;
        case HUFunctionViewShowMore:
        case HUFunctionViewShowFace:
            self.inputText = self.textView.text;
            [self.textView resignFirstResponder];

            break;
        case HUFunctionViewShowKeyboard:
           break;
        default:
            break;
    }
    
}
#pragma mark  切换输入状态 输入语音 表情 图片
- (void)showVoiceView:(BOOL)show{
    self.voiceButton.selected = show;
    self.voiceRecordButton.selected = show;
    self.voiceRecordButton.hidden = !show;
    if (show) {
        [self initTextViewFrame];
    }else{
    }
}
- (void)showFaceView:(BOOL)show{
    __weak typeof(self)weakSelf = self ;
    if (show) {
        [self.superView addSubview:self.faceView];
        [self.textView resignFirstResponder];
        CGRect changeFrame = weakSelf.frame;
        changeFrame.origin.y = _superFrame.size.height - kFunctionViewHeight - changeFrame.size.height;
        [weakSelf setFrame:changeFrame animated:NO];
        [UIView animateWithDuration:0.3 animations:^{
            
            _faceView.frame = CGRectMake(0, CGRectGetMaxY(weakSelf.frame), _superFrame.size.width, kFunctionViewHeight);
        }];
    }else{
        [UIView animateWithDuration:0.3 animations:^{
            _faceView.frame = CGRectMake(0, _superFrame.size.height, _superFrame.size.width, kFunctionViewHeight);
        }];
        [self.faceView removeFromSuperview];
    }
}
- (void)showMoreView:(BOOL)show{
    __weak typeof(self)weakSelf = self ;
    if (show) {
        [self.superView addSubview:self.moreView];
        [self.textView resignFirstResponder];
        CGRect changeFrame = weakSelf.frame;
        changeFrame.origin.y = _superFrame.size.height - kFunctionViewHeight - changeFrame.size.height;
        [weakSelf setFrame:changeFrame animated:NO];
        [UIView animateWithDuration:0.3 animations:^{
            _moreView.frame = CGRectMake(0, CGRectGetMaxY(weakSelf.frame), _superFrame.size.width, kFunctionViewHeight);
        }];
    }else{
        [UIView animateWithDuration:0.3 animations:^{
            _moreView.frame = CGRectMake(0, _superFrame.size.height, _superFrame.size.width, kFunctionViewHeight);
        }];
        [self.moreView removeFromSuperview];
    }
}

/**
 *  开始录音
 */
- (void)startRecordVoice{
    NSLog(@"开始录音");
}

/**
 *  取消录音
 */
- (void)cancelRecordVoice{
    NSLog(@"取消录音");
}

/**
 *  录音结束
 */
- (void)confirmRecordVoice{
   NSLog(@"录音结束");
}

/**
 *  更新录音显示状态,手指向上滑动后提示松开取消录音
 */
- (void)updateCancelRecordVoice{
   NSLog(@"更新录音显示状态,手指向上滑动后提示松开取消录音");
}

/**
 *  更新录音状态,手指重新滑动到范围内,提示向上取消录音
 */
- (void)updateContinueRecordVoice{
  
}
#pragma mark - HUFaceView 代理方法

- (void)faceViewSendFace:(NSString *)faceName{
    if ([faceName isEqualToString:@"[删除]"]) {
//        [self textView:self.textView shouldChangeTextInRange:NSMakeRange(self.textView.text.length - 1, 1) replacementText:@""];
        [self growingTextView:self.textView shouldChangeTextInRange:NSMakeRange(self.textView.text.length - 1, 1) replacementText:@""];
    }else if ([faceName isEqualToString:@"发送"]){
        NSString *text = self.textView.text;
        if (!text || text.length == 0) {
            return;
        }
//        if (self.delegate && [self.delegate respondsToSelector:@selector(chatBar:sendMessage:)]) {
//            [self.delegate chatBar:self sendMessage:text];
//        }
        self.inputText = @"";
        self.textView.text = @"";
        [self setFrame:CGRectMake(0, self.superFrame.size.height - KMinHeight, self.frame.size.width, KMinHeight) animated:NO];
        [self showViewWithType:HUFunctionViewShowFace];
    }else{
        self.textView.text = [self.textView.text stringByAppendingString:faceName];
    }
}
#pragma mark HUChatMoreView 代理方法
- (NSArray *)titlesOfMoreView:(HUChatMoreView *)moreView{
    return @[@"拍摄",@"照片",@"位置"];
}

- (NSArray *)imageNamesOfMoreView:(HUChatMoreView *)moreView{
    return @[@"chat_bar_icons_camera",@"chat_bar_icons_pic",@"chat_bar_icons_location"];
}
- (void)moreView:(HUChatMoreView *)moreView selectIndex:(HUChatMoreItemType)itemType {
    UIWindow* window = [[[UIApplication sharedApplication]delegate]window];
    switch (itemType) {
        case HUChatMoreItemCamera:{
            //显示拍照
            if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
                UIAlertController* alertController = [UIAlertController alertControllerWithTitle:@"" message:@"您的设备不支持拍照" preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction* action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil];
                [alertController addAction:action];
                [window.rootViewController presentViewController:alertController animated:YES completion:nil];
                break;
            }
            UIImagePickerController *pickerC = [[UIImagePickerController alloc] init];
            pickerC.sourceType = UIImagePickerControllerSourceTypeCamera;
            pickerC.delegate = self;
            [window.rootViewController presentViewController:pickerC animated:YES completion:nil];
            break;
        }
        case HUChatMoreItemAlbum:{
            //显示相册
            UIImagePickerController *pickerC = [[UIImagePickerController alloc] init];
            pickerC.delegate = self;
            [window.rootViewController presentViewController:pickerC animated:YES completion:nil];
            break;
        }
        case HUChatMoreItemLocation: {
            //显示地理位置
            break;
        }
            
        default:
            break;
    }
}
#pragma mark - UIImagePickerControllerDelegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    UIWindow* window = [[[UIApplication sharedApplication]delegate]window];
    UIImage *image = info[UIImagePickerControllerOriginalImage];
    [self sendImageMessage:image];
    [window.rootViewController dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    UIWindow* window = [[[UIApplication sharedApplication]delegate]window];
    [window.rootViewController dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - 输入框代理方法
- (BOOL)growingTextView:(HPGrowingTextView *)growingTextView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
//- (BOOL)textView:(HPGrowingTextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{

    if ([text isEqualToString:@"\n"]) {
        [self sendTextMessage:growingTextView.text];
        return NO;
    }else if (text.length == 0){
        //判断删除的文字是否符合表情文字规则
        NSString *deleteText = [growingTextView.text substringWithRange:range];
        if ([deleteText isEqualToString:@"]"]) {
            NSUInteger location = range.location;
            NSUInteger length = range.length;
            NSString *subText;
            while (YES) {
                if (location == 0) {
                    return YES;
                }
                location -- ;
                length ++ ;
                subText = [growingTextView.text substringWithRange:NSMakeRange(location, length)];
                if (([subText hasPrefix:@"["] && [subText hasSuffix:@"]"])) {
                    break;
                }
            }
            growingTextView.text = [growingTextView.text stringByReplacingCharactersInRange:NSMakeRange(location, length) withString:@""];
            [growingTextView setSelectedRange:NSMakeRange(location, 0)];
//            [self textViewDidChange:self.textView];
            return NO;
        }
    }
    return YES;
}


/**
 *  发送普通的文本信息,通知代理
 *
 *  @param text 发送的文本信息
 */
- (void)sendTextMessage:(NSString *)text{
    if (!text || text.length == 0) {
        return;
    }
    if (self.delegate && [self.delegate respondsToSelector:@selector(chatBar:sendMessage:)]) {
        [self.delegate chatBar:self sendMessage:text];
    }
    self.inputText = @"";
    self.textView.text = @"";
    [self setFrame:CGRectMake(0, self.superFrame.size.height - KMinHeight - KYYKeyBoard.keyboardFrame.size.height, self.frame.size.width, KMinHeight) animated:NO];
    [self showViewWithType:HUFunctionViewShowKeyboard];
}

/**
 *  通知代理发送语音信息
 *
 *  @param voiceData 发送的语音信息data
 *  @param seconds   语音时长
 */
- (void)sendVoiceMessage:(NSString *)voiceFileName seconds:(NSTimeInterval)seconds{
    if (self.delegate && [self.delegate respondsToSelector:@selector(chatBar:sendVoice:seconds:)]) {
        [self.delegate chatBar:self sendVoice:voiceFileName seconds:seconds];
    }
}

/**
 *  通知代理发送图片信息
 *
 *  @param image 发送的图片
 */
- (void)sendImageMessage:(UIImage *)image{
    if (self.delegate && [self.delegate respondsToSelector:@selector(chatBar:sendPictures:)]) {
        [self.delegate chatBar:self sendPictures:@[image]];
    }
}

#pragma mark 键盘随着输入高度增高
- (void)growingTextView:(HPGrowingTextView *)growingTextView willChangeHeight:(float)height {
    //返回当前输入框frame
    if (self.delegate&&[self.delegate respondsToSelector:@selector(chatBarFrameDidChange:frame:)]) {
        [self.delegate chatBarFrameDidChange:self frame:self.frame];
    }
    static float initValue = 36 ;
    float changeValue = height - initValue;
    
    if (changeValue != 0) {
        CGRect viewFrame = self.frame;
        viewFrame.origin.y -= changeValue;
        viewFrame.size.height += changeValue;
//        self.frame = viewFrame;
        [self setFrame:viewFrame animated:NO];
        initValue = height;
    }

}

#pragma mark SET && GET 
- (HPGrowingTextView *)textView{
    if (!_textView) {
        _textView = [[HPGrowingTextView alloc] init];
        _textView.font = [UIFont systemFontOfSize:16.0f];
        _textView.delegate = self;
        _textView.layer.cornerRadius = 4.0f;
        _textView.layer.borderColor = [UIColor colorWithRed:204.0/255.0f green:204.0/255.0f blue:204.0/255.0f alpha:1.0f].CGColor;
        _textView.returnKeyType = UIReturnKeySend;
        _textView.layer.borderWidth = .5f;
        _textView.layer.masksToBounds = YES;
    }
    return _textView;
}

- (UIButton *)voiceButton{
    if (!_voiceButton) {
        _voiceButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _voiceButton.tag = HUFunctionViewShowVoice;
        [_voiceButton setBackgroundImage:[UIImage imageNamed:@"chat_bar_voice_normal"] forState:UIControlStateNormal];
        [_voiceButton setBackgroundImage:[UIImage imageNamed:@"chat_bar_input_normal"] forState:UIControlStateSelected];
        [_voiceButton addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
        [_voiceButton sizeToFit];
    }
    return _voiceButton;
}

- (UIButton *)voiceRecordButton{
    if (!_voiceRecordButton) {
        _voiceRecordButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _voiceRecordButton.hidden = YES;
        _voiceRecordButton.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        [_voiceRecordButton setBackgroundColor:[UIColor lightGrayColor]];
        _voiceRecordButton.titleLabel.font = [UIFont systemFontOfSize:14.0f];
        [_voiceRecordButton setTitle:@"按住录音" forState:UIControlStateSelected];
        [_voiceRecordButton setTitle:@"松开发送录音" forState:UIControlStateNormal];
        [_voiceRecordButton addTarget:self action:@selector(startRecordVoice) forControlEvents:UIControlEventTouchDown];
        [_voiceRecordButton addTarget:self action:@selector(cancelRecordVoice) forControlEvents:UIControlEventTouchUpOutside];
        [_voiceRecordButton addTarget:self action:@selector(confirmRecordVoice) forControlEvents:UIControlEventTouchUpInside];
        [_voiceRecordButton addTarget:self action:@selector(updateCancelRecordVoice) forControlEvents:UIControlEventTouchDragExit];
        [_voiceRecordButton addTarget:self action:@selector(updateContinueRecordVoice) forControlEvents:UIControlEventTouchDragEnter];
    }
    return _voiceRecordButton;
}

- (UIButton *)moreButton{
    if (!_moreButton) {
        _moreButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _moreButton.tag = HUFunctionViewShowMore;
        [_moreButton setBackgroundImage:[UIImage imageNamed:@"chat_bar_more_normal"] forState:UIControlStateNormal];
        [_moreButton setBackgroundImage:[UIImage imageNamed:@"chat_bar_input_normal"] forState:UIControlStateSelected];
        [_moreButton addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
        [_moreButton sizeToFit];
    }
    return _moreButton;
}

- (UIButton *)faceButton{
    if (!_faceButton) {
        _faceButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _faceButton.tag = HUFunctionViewShowFace;
        [_faceButton setBackgroundImage:[UIImage imageNamed:@"chat_bar_face_normal"] forState:UIControlStateNormal];
        [_faceButton setBackgroundImage:[UIImage imageNamed:@"chat_bar_input_normal"] forState:UIControlStateSelected];
        [_faceButton addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
        [_faceButton sizeToFit];
    }
    return _faceButton;
}
- (HUFaceView *)faceView {
    if (!_faceView) {
        _faceView = [[HUFaceView alloc] initWithFrame:CGRectMake(0, self.superFrame.size.height, self.frame.size.width, kFunctionViewHeight)];
        _faceView.delegate = self ;
        _faceView.backgroundColor = self.backgroundColor ;
    }
    return _faceView;
}
- (UIView *)moreView {
    if (!_moreView) {
        _moreView = [[HUChatMoreView alloc] initWithFrame:CGRectMake(0, self.superFrame.size.height, self.frame.size.width, kFunctionViewHeight)];
        _moreView.delegate = self;
        _moreView.dataSource = self;
        _moreView.backgroundColor = self.backgroundColor;
    }
    return _moreView;
}
- (void)setFrame:(CGRect)frame animated:(BOOL)animated{
    if (animated) {
        [UIView animateWithDuration:.3 animations:^{
            [self setFrame:frame];
        }];
    }else{
        [self setFrame:frame];
    }
    if (self.delegate && [self.delegate respondsToSelector:@selector(chatBarFrameDidChange:frame:)]) {
        [self.delegate chatBarFrameDidChange:self frame:frame];
    }
}
@end
